<template>
  <div>
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="60%">
      <div class="diabianjireports">
        <div class="titlebox">
          <div></div>
          <div class="text">{{ reportvalue.powerName }} {{ reportvalue.dateString }} 光伏分析报告</div>
          <div class="butt">
            <el-button type="primary" size="small" @click="makepdf">生成pdf报告</el-button>
            <el-button type="primary" size="small" :disabled="entityvalue.createPdfFlag?false:true" @click="xiazaipdf">下载报告</el-button>
          </div>
        </div>
        <div class="titlebox">
          <div >单位名称：{{ reportvalue.powerName }}</div>
          <div class="text">报告类型: {{ reportvalue.dateType=='1'?'月报':'年报' }}</div>
          <div class="butt">时间: {{ reportvalue.dateString }}</div>
        </div>
        <el-divider></el-divider>
        <div class="oneji">一，运行情况</div>
        <div class="erji">
          <div class="tilt">1.整体概况</div>
          <div class="text">{{ reportvalue.powerName }}地址位于{{entityvalue.address}}，电站有{{entityvalue.inverterCount}}个逆变器。{{entityvalue.componentCount}}个组件等组成，
            装机容量为{{entityvalue.installationCapacity}}kWp，通过对该电站数据的采集分析，本电站发电量为{{entityvalue.actualGeneration}}kWh，等效发电
            小时为{{entityvalue.effectiveHours}}h，最大功率为{{entityvalue.actualGeneration}}kW，详情分析如下:
          </div>
        </div>
        <div class="erji">
          <div class="tilt">2.同环比分析</div>
          <div class="text">{{ reportvalue.powerName }}本期总发电量为{{entityvalue.actualGeneration}}kWh，同比降低{{ entityvalue.yearOnYear }}%，在发电量方面 {{ entityvalue.maxGenerationTime }}发电量最高为{{ entityvalue.maxGeneration }}kWh，
            {{ entityvalue.minGenerationTime }}发电量最低 为{{ entityvalue.minGeneration }}kWh；在发电功率方面 {{ entityvalue.maxPowerTime }}发电功率最高 为{{ entityvalue.maxPower }}kW，详情见下图:
          </div>
        </div>
        <div class="huanbibox" ref="huanbibox"></div>
        <div class="erji">
          <div class="tilt">3.逆变器等效小时分析</div>
          <div class="text">{{ reportvalue.powerName }}共有逆变器{{entityvalue.inverterCount}}台，通过等效小时数的离散率计算分析，本月发电等效小时数为优秀的逆变器有{{entityvalue.yxCount}}台 占比{{entityvalue.yxRatio}}%，
            良好的逆变器有{{entityvalue.lhCount}}台 占比{{entityvalue.lhRatio}}%，正常的逆变器有{{entityvalue.zcCount}}台 占比{{entityvalue.zcRatio}}%，
            较差的逆变器有{{entityvalue.jcCount}}台 占比{{entityvalue.jcRatio}}%，异常的逆变器有{{entityvalue.ycCount}}台 占比{{entityvalue.ycRatio}}%。
          </div>
        </div>
        <div class="dengxiaoxiaoshi" ref="dengxiaoxiaoshi"></div>
        <div class="erji">
          <div class="tilt">4.发电计划</div>
          <div class="text">本月计划发电为 {{entityvalue.planGeneration}}kWh，实际发电量为 {{entityvalue.actualGeneration}}kWh，完成率为 {{entityvalue.completionRate}}%，
            计划{{entityvalue.planGeneration>entityvalue.actualGeneration?'未':'已'}}完成
          </div>
        </div>
        <div class="jihuafdian" ref="jihuafdian"></div>
        <div class="erji">
          <div class="tilt">5.电站性能分析</div>
          <div class="text">{{ reportvalue.powerName }}本月电站性能(PR)为{{entityvalue.pr}}，详情见下图：
          </div>
        </div>
        <div class="xingnnegbox" ref="xingnnegbox"></div>
        <div class="erji">
          <div class="tilt">6.告警分析</div>
          <div class="text">{{ reportvalue.powerName }}本期共产生 条告警，详情见表格：
          </div>
        </div>
        <!-- 表格 -->
         <div style="margin: 20px 0;">
          <el-table
            :data="entityvalue.pesAlarmAnalyseList"
            border
            :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
            v-loading="loading"
            height="calc(100% - 1px)"
            style="width: 100%">
            <el-table-column
              type="index"
              align="center"
              width="80"
              label="序号">
            </el-table-column>
            <el-table-column
              prop="powerName"
              label="电站名称">
            </el-table-column>
            <el-table-column
              prop="deviceName"
              label="设备名称">
            </el-table-column>
            <el-table-column
              prop="alarmCount"
              align="right"
              label="告警条数">
            </el-table-column>
          </el-table>
         </div>
        <div class="erji">
          <div class="tilt">7.社会效益</div>
          <div class="text">光伏发电为绿色可再生能源{{ reportvalue.powerName }}本月发电详情：
          </div>
        </div>
        <div class="shehuixiaoyi" id="element">
           <div class="littlexiao">
             <div>
              <i class="iconfont icon-CO"></i>
             </div>
             <div>
              <div>减少二氧化碳(吨)</div>
              <div class="icon">{{ xiaoyivalue.cumulativeReductionCarbon }}</div>
             </div>
           </div>
           <div class="littlexiao">
            <div>
              <i class="iconfont icon-so2111"></i>
             </div>
             <div>
              <div>减少二氧化硫(吨)</div>
              <div class="so2111">{{ xiaoyivalue.cumulativeReductionSO2 }}</div>
             </div>
           </div>
           <div class="littlexiao">
            <div>
              <i class="iconfont icon-mei1"></i>
             </div>
             <div>
              <div>节约标煤(吨)</div>
              <div class="mei1">{{ xiaoyivalue.cumulativeReductionStandardCoal }}</div>
             </div>
           </div>
           <div class="littlexiao">
            <div>
              <i class="iconfont icon-senlin"></i>
             </div>
             <div>
              <div>减少森林砍伐(亩)</div>
              <div class="senlin">{{ xiaoyivalue.reductionForest }}</div>
             </div>
           </div>
        </div>
        <div class="oneji">二，运行优化建议</div>
        <div class="text">1.本月发电等效小时 
          <span v-if="entityvalue.jcCount">数异常或者较差的逆变器有 {{entityvalue.jcCount}}台</span>
          <span v-else>无异常或较差的逆变器</span>
           ，请结合实际情况进行排查</div>
        <div class="text">
          2.本月发电计划{{entityvalue.planGeneration>entityvalue.actualGeneration?'未':'已'}}完成, 
          <span v-if="entityvalue.planGeneration>entityvalue.actualGeneration">请结合天气 告警等因素分析原因</span> </div>
        <div class="text">3.本月电站平均性能(PR)为{{entityvalue.pr}}% 表现{{ entityvalue.pr>1?'不':'' }}符合预期</div>
        <div class="text">4.本月电站
          <span v-if="entityvalue.pesAlarmAnalyseList?.length">有{{ entityvalue.pesAlarmAnalyseList?.length }}条告警，请结合告警详情处理</span>
          <span v-else>无告警产生，整体运行情况良好</span>
        </div>
        <div class="oneji" style="margin-top: 20px;">三，说明</div>
        <div class="text">1.平台根据设备所采集的数据进行分析展示 作为电站运营的参考，不作为相关结算的依据；</div>
        <div class="text">2.平台依据气象仪的辐照度数据进行电站性能的计算，如电站没有辐照度数据则依据用户自身维护的峰值日照小时数进行计算，该值为经验值，可能跟实际情况有误差</div>
     </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import download from 'downloadjs'
import domToImage from 'dom-to-image';
import * as echarts from 'echarts';
import {getdianzhanxiangqingapi,getdianzhanhuanbiapi,getdianzhanxingnnegapi,postshengchengreportapi,getdianzhanxiaoyiapi} from '@/api/Photovoltaic/StatisticsReport/PhotovoltaicReport'
export default {
  name: 'CallPoliceBianjiReport',
  props: {
    reportvalue: {
      type: Object,
    },
    treevalue: {
      type: Object,
    },
    radio3: {
      type:String
    }
  },
  data() {
    return {
      dialogVisible: false,
      entityvalue: {},
      huanbiloading: null,
      dengxiaomyChart: null,
      xingnengmyChart:null,
      jihuamyChart: null,
      huanbimyChart: null,
      socialBenefitImage: '',
      tableData:[],
      loading: false,
      xiaoyivalue:{}
    };
  },

  mounted() {
    
  },

  methods: {
    // 产看报告
    async getbaogaolist() {
      // 获取基本信息
      this.loading=true
      const { data: { entity } } = await getdianzhanxiangqingapi({ id: this.reportvalue.id })
      this.entityvalue = entity
      this.loading=false
      // 同环比图表
      this.gettonghunabi()
      //等效小时图表
      this.gethournengxiao(entity)
      // 计划电量图表
      this.getdianzhanxiaolv(entity)
      // 电站性能图表
      this.getfadianlv()
      // 电站效益
      const res = await getdianzhanxiaoyiapi({
        dateString:this.reportvalue.dateString,dateType:this.reportvalue.dateType,classId:this.treevalue.id
      })
      this.xiaoyivalue=res.data.entity
    },
    // 下载报告
    xiazaipdf() {
      axios({
        method: 'POST',
        url:`/biz/pes-microservice-biz/pes/power/station/operation/report/download/pdf?id=${this.reportvalue.id}`,
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data], { type: 'application/pdf'})
        download(blob, `光伏分析报告.pdf`)
        })
    },
    // 生产报告
    async makepdf() {
      if(!this.huanbimyChart) return this.$message.warning('数据加载未完成')
      const effectiveHoursImage = this.dengxiaomyChart.getDataURL({
        pixelRatio:2,
        backgroundColor:'#fff'
      })
      const formanceAnalyseImage= this.xingnengmyChart.getDataURL({
        pixelRatio:2,
        backgroundColor:'#fff'
      })
      const planGenerationImage= this.jihuamyChart.getDataURL({
        pixelRatio:2,
        backgroundColor:'#fff'
      })
      const tbAnalyseImage= this.huanbimyChart.getDataURL({
        pixelRatio:2,
        backgroundColor:'#fff'
      })
      const palGradientGap = document.getElementById('element')
      const canvas = document.createElement('canvas')
      canvas.width = element.offsetWidth
      canvas.height = element.offsetHeight
      domToImage.toPng(element).then(async canvas => {
        await postshengchengreportapi({
          id:this.reportvalue.id,tbAnalyseImage,planGenerationImage,formanceAnalyseImage,effectiveHoursImage,socialBenefitImage:canvas
        }).then(res => {
          this.$message({
            type: res.code == '200' ? 'success' : 'warning',
            message: res.code == '200' ? '生成报告成功，当前可下载报告':res.message
          })
          this.$set(this.entityvalue,'createPdfFlag','1')
        })
      })
     },
    // 获取同环比图表
    async gettonghunabi() {
      var chartDom = this.$refs.huanbibox
      var myChart = echarts.init(chartDom);
      var option;
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        target: chartDom
      });
      const { data: { list } } = await getdianzhanhuanbiapi({
        dateString:this.reportvalue.dateString,dateType:this.reportvalue.dateType,classId:this.treevalue.id
      })
      const timePoints =[]
      for (let i = 0; i < list.length; i++) {
          if (list[i].datalist.length > 0) {
              list[i].datalist.forEach(data => {
                timePoints.push(data.timeReading);
              });
              break;
          }
      }
      option = {
        color:['#187cf5','#e6b75d','#c78ae6','#187cf5','#e6b75d','#c78ae6',],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '3%',
          // top: '8%',
          containLabel: true
        },
        legend: { },
        xAxis: [
          {
            type: 'category',
            data: timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '电量(kWh)',
          },
          {
            type: 'value',
            name: '负荷(kW)',
          }
        ],
        series: [
          {
            name: '本期电量',
            type: 'bar',
            data: list.filter(ele=>ele.name=='本期电量')[0].datalist.map(ele=>ele.valueReading)
          },
          {
            name: '上月同期电量',
            type: 'bar',
            data: list.filter(ele=>ele.name=='上月同期电量')[0].datalist.map(ele=>ele.valueReading)
          },
          {
            name: '去年同期电量',
            type: 'bar',
            data: list.filter(ele=>ele.name=='去年同期电量')[0].datalist.map(ele=>ele.valueReading)
          },
          {
            name: '本期负荷',
            type: 'line',
            smooth: true,
            yAxisIndex: 1,
            data: list.filter(ele=>ele.name=='本期负荷')[0].datalist.map(ele=>ele.valueReading)
          },
          {
            name: '上月同期负荷',
            type: 'line',
            smooth: true,
            yAxisIndex: 1,
            data: list.filter(ele=>ele.name=='上月同期负荷')[0].datalist.map(ele=>ele.valueReading)
          },
          {
            name: '去年同期负荷',
            type: 'line',
            smooth: true,
            yAxisIndex: 1,
            data: list.filter(ele=>ele.name=='去年同期负荷')[0].datalist.map(ele=>ele.valueReading)
          },
        ]
      };
      myChart.clear();
      option && myChart.setOption(option);
      this.huanbimyChart=myChart
      loading.close()
    },
    // 获取等效小时图表
    async gethournengxiao(val) {
      var chartDom = this.$refs.dengxiaoxiaoshi
      var myChart = echarts.init(chartDom);
      var option;
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        target: chartDom
      });
      const datalist = [
        { value: val.yxCount, name: '优秀' },
        { value: val.lhCount, name: '良好' },
        { value: val.zcCount, name: '正常' },
        { value: val.jcCount, name: '较差' },
        { value: val.ycCount, name: '异常' },
      ]
      option = {
        tooltip: {
          trigger: 'item'
        },
        color:['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae'],
        legend: {
          top: 'center',
          right: '20%',
          orient:'vertical',
          align:'right'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            padAngle: 1,
            itemStyle: {
              borderRadius: 10
            },
          label: {
            normal: {
              formatter:'{b}：{c}\n占比{d}%',
                rich: {
                c: {
                  color: "inherit",
                  fontSize: 10,
                  fontWeight: "bold",
                  lineHeight: 5,
                  },
                    b: {
                    fontSize: 18,
                    height: 40,
                  },
                },
              },
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true,
              length: 20,
              length2: 40,
              smooth: true
            },
            data:datalist
          }
        ]
      };
      myChart.clear();
      option && myChart.setOption(option);
      this.dengxiaomyChart=myChart;
      loading.close()
    },
    // 获取电站效率图表
    getdianzhanxiaolv(val) {
      var chartDom = this.$refs.jihuafdian
      var myChart = echarts.init(chartDom);
      var option;
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        target: chartDom
      });
      var fourPieData = [
        {
          name: "",
          max: val.planGeneration,
          value: val.actualGeneration,
        }
      ];
      var titleArr = [],
        seriesArr = [];
      let colors = [
        ["#187cf5", "#f4f4f7"],
      ];
      fourPieData.forEach(function(item, index) {
        titleArr.push({
          text: item.name,
          left: '50%',
          top: '90%',
          textAlign: "center",
          textStyle: {
            fontWeight: "normal",
            fontSize: "16",
            color: colors[index][0],
            textAlign: "center",
          },
        });
        seriesArr.push({
          name: item.name,
          type: "pie",
          clockWise: false,
          radius: ['50%', '70%'],
          itemStyle: {
            normal: {
              color: colors[index][0],
              shadowColor: colors[index][0],
              shadowBlur: 0,
              label: {
                show: true,
              },
              labelLine: {
                show: true,
              },
            },
          },
          hoverAnimation: false,
          center: ['50%','45%'],
          data: [
            {
              value: item.value,
              name: "发电量",
              label: {
                normal: {
                  formatter: function(params) {
                    let num = (val.actualGeneration/val.planGeneration * 100).toFixed(2);
                    return num+'%'
                  },
                  rich: {
                    a: {
                      color: "#000",
                      fontWeight: 500,
                      fontSize: 18,
                      lineHeight: 20,
                      align: "center",
                    },
                    b: {
                      color: "#000",
                      fontSize: 14,
                    },
                  },
                  position: "center",
                  show: true,
                  textStyle: {
                    fontSize: "20",
                    fontWeight: "bold",
                    color: colors[index][0], //跟随其他颜色
                  },
                },
              },
              itemStyle: {
                emphasis: {
                  color: colors[index][0],
                },
              },
            },
            {
              value: item.max - item.value,
              name: "总量",
              label: {
                show: false,
              },
              labelLine: {
                show: false,
              },
              itemStyle: {
                normal: {
                  color: colors[index][1],
                },
              },
            },
          ],
        });
      });
      option = {
          title: titleArr,
              series: seriesArr,
              tooltip: {
                trigger: "item",
                formatter: "{b}<br> {c}",
              },
      };
      myChart.clear();
      option && myChart.setOption(option);
      this.jihuamyChart= myChart;
      loading.close()
    },
    // 获取电站性能分析
    async getfadianlv() {
      var chartDom = this.$refs.xingnnegbox
      var myChart = echarts.init(chartDom);
      var option;
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        target: chartDom
      });
      const { data: { list } } = await getdianzhanxingnnegapi({
        dateString:this.reportvalue.dateString,dateType:this.reportvalue.dateType,classId:this.treevalue.id
      })
      const timePoints =[]
      for (let i = 0; i < list.length; i++) {
          if (list[i].datalist.length > 0) {
              list[i].datalist.forEach(data => {
                timePoints.push(data.timeReading);
              });
              break;
          }
      }
      option = {
        color:['#187cf5','#e6b75d','#d1a0ea'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          left: '2%',
          right: '1%',
          bottom: '3%',
          containLabel: true
        },
        legend: {},
        xAxis: [
          {
            type: 'category',
            data: timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '电量(kWh)',
            axisLine: {
              show: true
            }
          },
          {
            type: 'value',
            name: 'PR(%)',
            axisLine: {
              show: true
            }
          }
        ],
        series: [
          {
            name: '实际发电量',
            type: 'bar',
            data: list.filter(ele=>ele.name=='实际发电量')[0].datalist.map(ele=>ele.valueReading)
          },
          {
            name: '理论发电量',
            type: 'bar',
            data: list.filter(ele=>ele.name=='理论发电量')[0].datalist.map(ele=>ele.valueReading)
          },
          {
            name: '电站性能',
            type: 'line',
            smooth: true,
            yAxisIndex: 1,
            data:list.filter(ele=>ele.name=='Pr值')[0].datalist.map(ele=>ele.valueReading)
          }
        ]
      };
      myChart.clear();
      option && myChart.setOption(option);
      this.xingnengmyChart=myChart;
      loading.close()
    },
  },
};
</script>

<style scoped>
.diabianjireports{
  /* font-size: 16px; */
  color: #293343;
  .titlebox{
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .butt{
      text-align: right;
    }
    .text{
      text-align: center;
    }
    div{
      width: 33.3%;
    }
  }
  .oneji{
    font-size: 18px;
    color: #000;
    margin-bottom: 15px;
  }
  .erji{
    margin-bottom: 15px;
    .tilt{
      font-size: 16px;
      color: #000;
      margin-bottom: 10px;
    }

  }
  .text{
        font-size: 14px;
        text-indent: 20px;
      }
  .huanbibox, .dengxiaoxiaoshi, .jihuafdian, .xingnnegbox{
    height: 300px;
    margin-bottom: 20px;
  }
  .shehuixiaoyi{
    height: 60px;
    margin-bottom: 20px;
    display: flex;
    .littlexiao{
      width: 25%;
      /* line-height: 60px; */
      display: flex;
      justify-content: center;
      align-items: center;
      .iconfont{
        font-size: 60px;
        margin-right: 10px;
      }
      .icon-CO, .icon{
        color: #e0b943;
      }
      .icon-so2111, .so2111{
        color: #e07843;
      }
      .icon-mei1, .mei1{
        color: #187cf5;
      }
      .icon-senlin, .senlin{
        color: #1f995c;
      }
    }
  }
}
::v-deep .el-dialog__footer{
  text-align:center;
}
</style>